package com.sum.common.utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.SoundPool;

import com.sum.common.R;

public class SoundUtils {
    private static SoundPool soundPool;
    private static final int MAX_STREAMS = 10;
    private static final int SOUND_PRIORITY = 1;
    private static final float SOUND_RATE = 1.0f;
    private static final float SOUND_VOLUME = 1.0f;
    private static final int SOUND_LOOP = 0;

    private SoundUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 初始化音频播放池
     * @param context 上下文
     */
    public static void initSoundPool(Context context) {
        if (context == null) {
            return;
        }

        // 创建AudioAttributes
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

        // 创建SoundPool
        soundPool = new SoundPool.Builder()
                .setMaxStreams(MAX_STREAMS)
                .setAudioAttributes(audioAttributes)
                .build();

        // 加载音频资源
        if (soundPool != null) {
            soundPool.load(context, R.raw.beep333, SOUND_PRIORITY);
        }
    }

    /**
     * 播放声音
     */
    public static void playSound() {
        if (soundPool != null) {
            soundPool.play(SOUND_PRIORITY, SOUND_VOLUME, SOUND_VOLUME,
                    SOUND_PRIORITY, SOUND_LOOP, SOUND_RATE);
        }
    }

    /**
     * 释放资源
     */
    public static void release() {
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
    }
}